<?php

namespace App\Http\Controllers\Admin;

use App\Jobs\SendChangeOrderMessage;
use App\Models\Logistics;
use App\Models\NewAdmin;
use App\Models\Order;
use App\Models\OrderLease;
use App\Models\OrderLeaseAudit;
use App\Models\OrderLog;
use App\Models\OrderRate;
use App\Models\OrderRefund;
use App\Models\OrderRefundAudit;
use App\Models\OrderReturn;
use App\Models\OtherWithholdLog;
use App\Models\ShopSms;
use App\Models\ShopUser;
use App\Services\AlipayMessageService;
use App\Services\AlipayService;
use App\Services\AntchainAtoService;
use App\Services\AntchainService;
use App\Services\AuthService;
use App\Services\CommonService;
use App\Services\EsignService;
use App\Services\GoodsService;
use App\Services\LogisticsService;
use App\Services\OrderService;
use App\Services\OtherCallbacksService;
use App\Services\WechatService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class OrderRefundController extends BaseController
{

    /**
     * 订单退款列表
     */
    public function orderRefundList(Request $request){
        $request_data = $request->all();
        if($this->users['role_id']=='47'){
            $request_data['order_status']=8;
        }
        $list = OrderRefund::orderRefundList($request_data,OrderRefund::ORDER_REFUND_TYPE_ONLY_REFUND);
        if(!empty($list) && !empty($list['data'])){
            foreach ($list['data'] as $k=>$v){
                $list['data'][$k]['refund_status_name'] = OrderRefund::ORDER_REFUND_STATUS_NAME_LIST[$v['refund_status']];
            }
        }
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功',$list);
    }



    /**
     * 退款详情
     */
    public function orderRefundInfo(Request $request){
        $order_id = $request->input('order_id');
        if(!empty($order_id)){
            $order_refund = OrderRefund::from('sp_order_refund as or')->where('o.id',$order_id)
                ->leftjoin('sp_order_2 as o','or.order_id','o.id')
                ->leftjoin('sp_order_goods_2 as og','og.order_id','o.id')
                ->leftjoin('sp_member_2 as m','m.id','o.uid')
                ->select('or.id','m.mobile','m.cert_name','m.cert_no','o.trade_no','or.create_time','or.refund_amount','or.deduct_amount','or.paid_total_rent','og.goods_title','og.imgurl','og.setmeal_title','o.amount','og.lease_set','og.lease_time','o.rent_total','or.refund_type','or.refund_reason','or.refund_desc','or.refund_image','or.refund_status')->orderBy('or.id','desc')->first();
            $order_refund = obToArray($order_refund);
            if(!empty($order_refund)){
                $order_refund['refund_status_name'] = OrderRefund::ORDER_REFUND_STATUS_NAME_LIST[$order_refund['refund_status']];
            }
            $order_refund['order_log'] = OrderLog::getOrderLogByOrderId($order_id);
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功',$order_refund);
        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请选择要查看的订单');
        }
    }


    /**
     * 退款订单补足金额明细
     */
    public function orderRefundTransData(Request $request){
        $refund_id = $request->input('refund_id');
        if(!empty($refund_id)){
            $order_refund = OrderRefund::from('sp_order_refund as or')->where('or.id',$refund_id)
                ->leftjoin('sp_order_2 as o','or.order_id','o.id')
                ->leftjoin('sp_order_goods_2 as og','og.order_id','o.id')
                ->leftjoin('sp_shop_user_2 as s','s.member_id','o.seller_id')
                ->leftjoin('sp_order_rate as oe','oe.order_id','or.order_id')
                ->select('or.id','or.order_id','o.trade_no','o.pay_type','o.month_total','o.rent_total','or.deduct_amount','or.paid_total_rent','or.refund_amount','o.is_skip','o.financing_type','og.goods_id','o.month_total','o.status','o.rights_auth_no','o.alipay_trade_no','o.seller_id','o.uid','o.order_from','s.shop_balance','og.goods_title','o.payer_user_id','o.settlement_status','o.pay_time','s.shopname','oe.fixed_amount','oe.shop_rate','oe.platform_rate','oe.withhold_rate','oe.file_rate','oe.financing_rate','oe.insure_rate','oe.huabei_rate','o.huabei_stages')->first();
            $order_refund = obToArray($order_refund);
            if(!empty($order_refund)){
                $insure_fee = 0;
                $data['refund_id'] = $order_refund['id'];
                $data['trade_no'] = $order_refund['trade_no'];
                $data['pay_type'] = OrderLease::ORDER_LEASE_PAY_TYPE_LIST[$order_refund['pay_type']];
                $data['month_total'] = $order_refund['month_total'];
                $data['rent_total'] = $order_refund['rent_total'];
                $data['paid_total_rent'] = $order_refund['paid_total_rent'];
                if($order_refund['is_skip'] == Order::RISK_SKIP_YES){
                    $data['is_risk'] = '否';
                }else{
                    $data['is_risk'] = '是';
                }
                $data['financing_type'] = Order::FINANCING_TYPE_LIST[$order_refund['financing_type']];
                $data['insure_fee'] = $insure_fee;
                $data['refund_amount'] = $order_refund['refund_amount'];
                $data['paid_service_fee'] = 0;
                $data['total_service_fee'] = 0;
                $order_lease = OrderLease::where('order_id',$order_refund['order_id'])->select('id','status','settle_type','paid_rent','which_period','rent')->get();
                $order_lease = obToArray($order_lease);
                $data['deduct_refund_amount'] = 0;
                $data['deduct_service_fee'] = 0;
                if($order_refund['huabei_fee_bear'] == GoodsService::GOODS_HUABEI_FEE_MERCHANT && $order_refund['pay_time'] + 15*24*3600 > time()){
                    $order_refund['shop_rate'] = $order_refund['shop_rate'] - $order_refund['huabei_rate'];
                }
                if($order_lease){
                    foreach ($order_lease as $k=>$v){
                        if($v['status'] == OrderLease::ORDER_LEASE_STATUS_PAID || $v['status'] == OrderLease::ORDER_LEASE_STATUS_REFUNDED || $v['status'] == OrderLease::ORDER_LEASE_STATUS_BUYOUT){
                            $shop_rate = $order_refund['shop_rate'];
                        }else{
                            if($order_refund['financing_type'] == Order::FINANCING_TYPE_RONG){//融资
                                    $shop_rate = $order_refund['file_rate'] + $order_refund['financing_rate'] + $order_refund['insure_rate'];
                            }
                        }
                        if($v['settle_type'] == OrderLease::ORDER_LEASE_SETTLE_STATUS_YES){
                            if($v['status'] != OrderLease::ORDER_LEASE_STATUS_REFUNDED){
                                $data['deduct_refund_amount'] += $v['paid_rent'];
                            }
                            if($v['which_period'] == 1){
                                $service_fee = sprintf("%01.4f",$v['paid_rent'] * $shop_rate * 0.01 + $order_refund['fixed_amount']);
                            }else{
                                $service_fee = sprintf("%01.4f",$v['paid_rent'] * $shop_rate * 0.01);
                            }
                            $data['paid_service_fee'] += $service_fee;
                            $data['total_service_fee'] += $service_fee;
                        }else{
                            if($v['status'] == OrderLease::ORDER_LEASE_STATUS_REFUNDED){
                                if($v['which_period'] == 1){
                                    $data['paid_service_fee'] += $order_refund['fixed_amount'];
                                    $data['total_service_fee'] += $order_refund['fixed_amount'];
                                }
                            }else{
                                $data['paid_service_fee'] += 0;
                                $data['deduct_service_fee'] += 0;
                                if($v['which_period'] == 1){
                                    $data['deduct_service_fee'] += $order_refund['fixed_amount'];
                                    $data['total_service_fee'] += $order_refund['fixed_amount'];
                                }
                            }
                        }
                    }
                }

                $data['deduct_amount'] = sprintf("%01.4f",$data['deduct_refund_amount'] + $data['deduct_service_fee']);
                return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功',$data);
            }else{
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单不存在');
            }
        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请选择要查看的订单');
        }
    }


    /**
     * 退款账单明细
     */
    public function orderRefundDetail(Request $request){
        $refund_id = $request->input('refund_id');
        if(!empty($refund_id)){
            $order = OrderLease::from('sp_order_lease_2 as ol')->where('or.id',$refund_id)
                ->leftjoin('sp_order_refund as or','or.order_id','ol.order_id')
                ->leftjoin('sp_order_rate as oe','oe.order_id','ol.order_id')
                ->leftjoin('sp_order_2 as o','o.id','ol.order_id')
                ->select('ol.id','o.is_skip','o.trade_no','o.financing_type','ol.which_period','ol.pay_type','ol.settle_type','ol.status','ol.settle_amount','ol.rent','ol.paid_rent','oe.platform_rate','oe.shop_rate','oe.fixed_amount','oe.smartcontract_amount','oe.realname_amount','oe.risk_amount','oe.platform_rate','oe.withhold_rate','oe.file_rate','oe.financing_rate','oe.insure_rate','oe.huabei_rate','o.pay_time')->get();
            $order = obToArray($order);
            if(!empty($order)){
                $total_payable_fee = 0;
                $total_paid_fee = 0;
                $total_refund_amount = 0;
                $total_deduct_fee = 0;
                $total_deduct_amount = 0;
                foreach ($order as $k=>$v){
                    $order[$k]['paid_fee'] = 0;
                    $order[$k]['refund_amount'] = 0;
                    $order[$k]['deduct_amount'] = 0;
                    $order[$k]['deduct_refund_amount'] = 0;
                    $order[$k]['deduct_fee'] = 0;
                    $order[$k]['payable_fee'] = 0;
                    if($v['huabei_fee_bear'] == GoodsService::GOODS_HUABEI_FEE_MERCHANT && $v['pay_time'] + 15*24*3600 > time()){
                        $shop_rate = $v['shop_rate'] - $v['huabei_rate'];
                    }else{
                        $shop_rate = $v['shop_rate'];
                    }
                    if($v['which_period'] == 1){//首期
                        if($v['settle_type'] != OrderLease::ORDER_LEASE_SETTLE_STATUS_YES){//未结算
                            $order[$k]['withhold_rate'] = 0;
                            $order[$k]['file_rate'] = 0;
                            $order[$k]['platform_rate'] = 0;
                            $shop_rate = 0;
                            $order[$k]['payable_fee'] = $v['fixed_amount'];
                        }else{
                            $order[$k]['payable_fee'] = sprintf("%01.4f",$v['rent'] * $shop_rate * 0.01 + $v['fixed_amount']);
                        }
                    }else{
                        $order[$k]['smartcontract_amount'] = 0;
                        $order[$k]['realname_amount'] = 0;
                        $order[$k]['risk_amount'] = 0;
                        if($v['financing_type'] == Order::FINANCING_TYPE_RONG) {//融资
                            if($v['status'] != OrderLease::ORDER_LEASE_STATUS_NOPAY){
                                $order[$k]['withhold_rate'] = 0;
                                $order[$k]['platform_rate'] = 0;
                                $shop_rate = $v['financing_rate'];
                                $order[$k]['shop_rate'] = $shop_rate;
                                $order[$k]['payable_fee'] = sprintf("%01.4f",$v['rent'] * $shop_rate * 0.01);
                            }
                        }else{
                            if($v['settle_type'] == OrderLease::ORDER_LEASE_SETTLE_STATUS_YES){//已结算
                                $order[$k]['payable_fee'] = sprintf("%01.4f",$v['rent'] * $shop_rate * 0.01);
                            }else{
                                $order[$k]['payable_fee'] = 0;
                            }
                        }
                    }

                    $order[$k]['pay_type'] = OrderLease::ORDER_LEASE_PAY_TYPE_LIST[$v['pay_type']];
                    if($v['status'] != OrderLease::ORDER_LEASE_STATUS_NOPAY){
                        $order[$k]['refund_amount'] = $v['paid_rent'];
                    }
                    if($v['settle_type'] == OrderLease::ORDER_LEASE_SETTLE_STATUS_YES){//已结算
                        $order[$k]['paid_fee'] = $order[$k]['payable_fee'];
                    }else{
                        if($v['status'] == OrderLease::ORDER_LEASE_STATUS_REFUNDED){
                            $order[$k]['paid_fee'] = $order[$k]['payable_fee'];
                        }
                    }
                    $order[$k]['pay_status'] = OrderLease::ORDER_LEASE_STATUS_LIST[$v['status']];
                    $order[$k]['settle_status_name'] = OrderLease::ORDER_LEASE_SETTLE_STATUS_LIST[$v['settle_type']];
                    $order[$k]['lease_status_name'] = OrderLease::ORDER_LEASE_STATUS_LIST[$v['status']];
                    if($v['status'] == OrderLease::ORDER_LEASE_STATUS_NOPAY){

                    }else{
                        $order[$k]['deduct_fee'] = sprintf("%01.4f",$order[$k]['payable_fee'] - $order[$k]['paid_fee']);
                    }
                    if($v['settle_type'] == OrderLease::ORDER_LEASE_SETTLE_STATUS_YES && $v['status'] != OrderLease::ORDER_LEASE_STATUS_REFUNDED){
                        $order[$k]['deduct_refund_amount'] = $v['paid_rent'];
                    }
                    $order[$k]['shop_rate'] = $shop_rate;
                    $total_payable_fee += $order[$k]['payable_fee'];
                    $total_paid_fee += $order[$k]['paid_fee'];
                    $total_refund_amount += $order[$k]['refund_amount'];
                    $total_deduct_fee += $order[$k]['deduct_fee'];
                    $total_deduct_amount += $order[$k]['deduct_refund_amount'];
                }
                $order['total_payable_fee'] = sprintf("%01.4f",$total_payable_fee);
                $order['total_paid_fee'] = sprintf("%01.4f",$total_paid_fee);
                $order['total_refund_amount'] = sprintf("%01.4f",$total_refund_amount);
                $order['total_deduct_fee'] = sprintf("%01.4f",$total_deduct_fee);
                $order['total_deduct_amount'] = sprintf("%01.4f",$total_deduct_amount);
            }
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功',$order);
        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请选择要查看的订单');
        }
    }

    /**
     * 订单退款 - 商户审核通过
     */
    public function shopCheckPass(Request $request)
    {
        $refund_id = $request->input('refund_id');
        if (!empty($refund_id)) {
            $order = OrderRefund::from('sp_order_refund as or')->where([['or.id', $refund_id], ['or.refund_status', OrderRefund::ORDER_REFUND_NOCHECK]])
                ->wherein('o.status', OrderService::getOrderStatus(OrderService::ORDER_REFUND_CHECK_STATUS))
                ->leftjoin('sp_order_2 as o', 'or.order_id', 'o.id')
                ->leftjoin('sp_shop_user_2 as s', 's.member_id', 'o.seller_id')
                ->leftjoin('sp_order_goods_2 as og', 'og.order_id', 'o.id')
                ->select('or.id', 'o.mini_id', 'o.uid', 'o.mini_id', 'or.order_id', 'o.realname', 'o.create_time', 'o.mobile', 'or.refund_reason',
                    'o.pay_type', 'o.status', 'o.rent_total', 'o.rights_auth_no', 'o.trade_no', 'o.alipay_trade_no', 'o.sign_no',
                    'o.seller_id', 'o.month_total', 'o.uid', 'o.order_from', 'o.financing_type', 'o.is_skip',
                    's.shop_balance', 'og.goods_title', 'o.payer_user_id', 'og.goods_id', 'o.settlement_status',
                     'o.pay_time', 's.refund_check', 's.shopname', 'or.deduct_amount', 'o.flow_id', 'o.rights_auth_no', 'o.alipay_trade_no')
                ->first();
            $order = $order ? $order->toArray() : [];
            if (!empty($order)) {
                // if(OrderRate::where('order_id',$order['order_id'])->count() == 0){
                //     return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单来源费率未设置');
                // }

                $miniId = $order['mini_id'];

                if ($order['deduct_amount'] > ShopUser::where('member_id', $order['seller_id'])->value('shop_balance')) {
                    return ReturnMsg(CommonService::HTTP_CODE_REFUND, '商户余额不足，请充值后再退款');
                }
                if ($order['refund_check'] == ShopUser::ORDER_REFUND_ADMIN_CHECK_ENABLE) {//需要平台审核 提交至平台审核
                    $res = OrderRefund::where('id', $refund_id)->update(['refund_status' => OrderRefund::ORDER_REFUND_SHOP_CHECKED]);
                    $order_res = Order::where('id', $order['order_id'])->update(['status' => OrderService::ORDER_STATUS_APPLY_REFUND_SHOP_PASS, 'update_time' => time()]);
                    if ($res && $order_res) {
                        OrderLog::addOrderLog($order['order_id'], $this->users['id'], OrderLog::ORDER_LOG_OPERATE_TYPE_ADMIN, '订单退款-商户审核通过');
                        if (!empty($order['rights_auth_no'] && $order['alipay_trade_no']) && $order['status'] <= OrderService::ORDER_STATUS_PAY_SUCCESS) {//解冻预授权，作废合同

                            $alipay_data['alipayTradeNo'] = $order['alipay_trade_no'];
                            $alipay_data['authNo'] = $order['rights_auth_no'];
                            $prequery = AlipayService::alipayPreQuery($miniId, $alipay_data);
                            if ($prequery['status']) {
                                $rest_amount = $prequery['data']['rest_amount'];//订单总共剩余的冻结金额
                                if ($rest_amount > 0) { //冻结金额大于0  执行解冻操作
                                    $thaw_data['amount'] = $rest_amount;
                                    $thaw_data['authNo'] = $order['rights_auth_no'];
                                    $thaw_query = AlipayService::alipayPreThaw($miniId, $thaw_data);
                                    if ($thaw_query['status'] && $thaw_query['data']['code'] == AlipayService::ALIPAY_SUCCESS_CODE) { //解冻成功
                                        if (!empty($order['flow_id']) && $order['sign_status'] == EsignService::ESIGN_STATUS_SIGNING) {//合同未签署完成撤销
                                            EsignService::revoke($order['flow_id']);
                                        }
                                        //查找扣款失败未履约的订单
                                        $log = OtherWithholdLog::where(['order_no' => $order['trade_no'], 'status' => 0])->whereIn('pay_type', [OtherWithholdLog::PAY_TYPE_ZM, OtherWithholdLog::PAY_TYPE_MANUAL_ZM])
                                            ->groupBy('out_trade_no')
                                            ->get();
                                        foreach ($log as $value) {
                                            $orderData = [
                                                'orderId' => $value['order_no'],
                                                'outTradeNo' => $value['out_trade_no'],
                                                'tradeNo' => $value['trade_no'],
                                                'status' => 'CLOSED',
                                            ];
                                            AlipayService::orderInfo($miniId, $orderData);
                                        }
                                        $user_order_count = Order::where('uid', $order['uid'])->whereIn('status', OrderService::getOrderStatus(OrderService::ORDER_MANUAL_WITHHOLD_OR_PAY))->sum('amount');
                                        Order::where('uid', $order['uid'])->whereIn('status', OrderService::getOrderStatus(OrderService::ORDER_MANUAL_WITHHOLD_OR_PAY))->update(['user_order_count' => $user_order_count]);
                                    } else {
                                        return ['status' => CommonService::HTTP_CODE_FAIL, 'msg' => '授权资金解冻失败，请联系平台客服解决', 'data' => []];
                                    }
                                }
                            } else {
                                return ['status' => CommonService::HTTP_CODE_FAIL, 'msg' => '未查到授权资金解冻，请联系平台客服解决', 'data' => []];
                            }
                        }
                        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '审核成功');
                    } else {
                        return ReturnMsg(CommonService::HTTP_CODE_FAIL, '审核失败');
                    }
                } elseif ($order['refund_check'] == ShopUser::ORDER_REFUND_ADMIN_CHECK_DISABLE) {//不需要平台审核   直接退款
                    $order_lease = OrderLease::where([['order_id', $order['order_id']], ['status', OrderLease::ORDER_LEASE_STATUS_PAID]])->select('id')->get();
                    $order_lease = $order_lease ? $order_lease->toArray() : [];
                    $lease_id_arr = array_column($order_lease, 'id');
                    $res = OrderRefund::orderRefund($order, $lease_id_arr, OrderRefund::ORDER_REFUND_REQUEST_TYPE_XXZ, OrderRefund::ORDER_REFUND_ALLIN);
                    // dd($res);
                    if ($res['status'] == CommonService::HTTP_CODE_SUCCESS) {
                        $user_order_count = Order::where('uid', $order['uid'])->whereIn('status', OrderService::getOrderStatus(OrderService::ORDER_MANUAL_WITHHOLD_OR_PAY))->count();
                        Order::where('uid', $order['uid'])->whereIn('status', OrderService::getOrderStatus(OrderService::ORDER_MANUAL_WITHHOLD_OR_PAY))->update(['user_order_count' => $user_order_count]);
                        OrderLog::addOrderLog($order['order_id'], $this->users['id'], OrderLog::ORDER_LOG_OPERATE_TYPE_ADMIN, '订单退款-商户审核通过');
                        OtherCallbacksService::orderRefundNotify($order['order_id'], date('Y-m-d H:i:s'));
                        //退款成功短信通知
                        ShopSms::orderRefundSuccess($order['seller_id'], $order['realname'], $order['trade_no'], $order['mobile'], $order['order_id'], $this->users['id']);
                        if (!empty($order['rights_auth_no'] && $order['alipay_trade_no']) && $order['status'] <= OrderService::ORDER_STATUS_PAY_SUCCESS) {//解冻预授权，作废合同
                            $alipay_data['alipayTradeNo'] = $order['alipay_trade_no'];
                            $alipay_data['authNo'] = $order['rights_auth_no'];
                            $prequery = AlipayService::alipayPreQuery($miniId, $alipay_data);
                            if ($prequery['status']) {
                                $rest_amount = $prequery['data']['rest_amount'];//订单总共剩余的冻结金额
                                if ($rest_amount > 0) { //冻结金额大于0  执行解冻操作
                                    $thaw_data['amount'] = $rest_amount;
                                    $thaw_data['authNo'] = $order['rights_auth_no'];
                                    $thaw_query = AlipayService::alipayPreThaw($miniId, $thaw_data);
                                    if ($thaw_query['status'] && $thaw_query['data']['code'] == AlipayService::ALIPAY_SUCCESS_CODE) { //解冻成功
                                        if (!empty($order['flow_id']) && $order['sign_status'] == EsignService::ESIGN_STATUS_SIGNING) {//合同未签署完成撤销
                                            EsignService::revoke($order['flow_id']);
                                        }
                                        //查找扣款失败未履约的订单
                                        $log = OtherWithholdLog::where(['order_no' => $order['trade_no'], 'status' => 0])->whereIn('pay_type', [OtherWithholdLog::PAY_TYPE_ZM, OtherWithholdLog::PAY_TYPE_MANUAL_ZM])
                                            ->groupBy('out_trade_no')
                                            ->get();
                                        foreach ($log as $value) {
                                            $orderData = [
                                                'orderId' => $value['order_no'],
                                                'outTradeNo' => $value['out_trade_no'],
                                                'tradeNo' => $value['trade_no'],
                                                'status' => 'CLOSED',
                                            ];
                                            AlipayService::orderInfo($miniId, $orderData);
                                        }
                                        $user_order_count = Order::where('uid', $order['uid'])->whereIn('status', OrderService::getOrderStatus(OrderService::ORDER_MANUAL_WITHHOLD_OR_PAY))->sum('amount');
                                        Order::where('uid', $order['uid'])->whereIn('status', OrderService::getOrderStatus(OrderService::ORDER_MANUAL_WITHHOLD_OR_PAY))->update(['user_order_count' => $user_order_count]);
                                    } else {
                                        return ['status' => CommonService::HTTP_CODE_FAIL, 'msg' => '授权资金解冻失败，请联系平台客服解决', 'data' => []];
                                    }
                                }
                            } else {
                                return ['status' => CommonService::HTTP_CODE_FAIL, 'msg' => '未查到授权资金解冻，请联系平台客服解决', 'data' => []];
                            }
                        }
                        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '退款成功');
                    } else {
                        return ReturnMsg(CommonService::HTTP_CODE_FAIL, $res['msg'], $res);
                    }
                }
            } else {
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单不存在');
            }
        } else {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请选择要操作的订单');
        }
    }


    /**
     * 订单退款 - 商户审核拒绝
     */
    public function shopCheckRefuse(Request $request){
        $refund_id = $request->input('refund_id');
        $refuse_reason = $request->input('refuse_reason');
        if(!empty($refund_id) && !empty($refuse_reason)){
            $order_id = OrderRefund::where([['id',$refund_id],['refund_status',OrderRefund::ORDER_REFUND_NOCHECK]])->value('order_id');
            if(!empty($order_id)){
                $data['refuse_reason'] = $refuse_reason;
                $data['refund_status'] = OrderRefund::ORDER_REFUND_SHOP_REFUSE;
                $res = OrderRefund::where('id',$refund_id)->update($data);
                $order_res = Order::where('id',$order_id)->update(['status'=>OrderService::ORDER_STATUS_APPLY_REFUND_SHOP_REFUSE,'update_time'=>time()]);
                if($res && $order_res){
                    OrderLog::addOrderLog($order_id,$this->users['id'],OrderLog::ORDER_LOG_OPERATE_TYPE_ADMIN,'订单退款-商户审核拒绝');
                    return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'审核拒绝成功');
                }else{
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL, '审核拒绝失败');
                }
            }else{
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '退款订单不存在或不是待审核状态');
            }
        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请选择要操作的订单并填写拒绝原因');
        }
    }


    /**
     * 订单退款 - 平台审核通过
     */
    public function adminCheckPass(Request $request){
        $refund_id = $request->input('refund_id');
        if(!empty($refund_id)){
            $order = OrderRefund::from('sp_order_refund as or')->where([['or.id',$refund_id],['or.refund_status',OrderRefund::ORDER_REFUND_SHOP_CHECKED]])
                ->leftjoin('sp_order_2 as o','or.order_id','o.id')
                ->leftjoin('sp_shop_user_2 as s','s.member_id','o.seller_id')
                ->leftjoin('sp_order_goods_2 as og','og.order_id','o.id')
                ->select('or.id', 'o.mini_id', 'o.uid', 'or.order_id', 'o.realname', 'o.mobile', 'o.pay_type', 'o.status', 'o.rent_total', 'o.rights_auth_no', 'o.trade_no', 'o.alipay_trade_no', 'o.seller_id', 'o.month_total', 'o.uid', 'o.order_from', 'o.financing_type', 'o.is_skip', 's.shop_balance', 'og.goods_title', 'o.payer_user_id', 'og.goods_id', 'o.settlement_status',  'o.pay_time', 's.refund_check', 's.shopname', 'or.deduct_amount', 'o.flow_id')
                ->first();
            $order = $order ? $order->toArray() : [];
            if(!empty($order)){
                // if(OrderRate::where('order_id',$order['order_id'])->count() == 0){
                //     return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单来源费率未设置');
                // }
                if($order['deduct_amount'] > ShopUser::where('member_id',$order['seller_id'])->value('shop_balance')){
                    return ReturnMsg(CommonService::HTTP_CODE_REFUND, '商户余额不足，请充值后再退款');
                }
                $order_lease = OrderLease::where([['order_id',$order['order_id']],['status',OrderLease::ORDER_LEASE_STATUS_PAID]])->select('id')->get();
                $order_lease = $order_lease ? $order_lease->toArray() : [];
                $lease_id_arr = array_column($order_lease,'id');
                $res = OrderRefund::orderRefund($order,$lease_id_arr,OrderRefund::ORDER_REFUND_REQUEST_TYPE_XXZ,OrderRefund::ORDER_REFUND_ALLIN);
                if($res['status'] == CommonService::HTTP_CODE_SUCCESS){
                    $user_order_count = Order::where('uid',$order['uid'])->whereIn('status',OrderService::getOrderStatus(OrderService::ORDER_MANUAL_WITHHOLD_OR_PAY))->count();
                    Order::where('uid',$order['uid'])->whereIn('status',OrderService::getOrderStatus(OrderService::ORDER_MANUAL_WITHHOLD_OR_PAY))->update(['user_order_count'=>$user_order_count]);
                    OrderLog::addOrderLog($order['order_id'],$this->users['id'],OrderLog::ORDER_LOG_OPERATE_TYPE_ADMIN,'订单退款-平台审核通过');
                    OtherCallbacksService::orderRefundNotify($order['order_id'],date('Y-m-d H:i:s'));
                    //退款成功短信通知
                    ShopSms::orderRefundSuccess($order['seller_id'],$order['realname'],$order['trade_no'],$order['mobile'],$order['order_id'],$this->users['id']);
                    return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'退款成功');
                }else{
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL,'退款失败',$res);
                }
            }else{
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单不存在');
            }
        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请选择要操作的订单');
        }
    }


    /**
     * 订单退款 - 平台审核拒绝
     */
    public function adminCheckRefuse(Request $request){
        $refund_id = $request->input('refund_id');
        $refuse_reason = $request->input('refuse_reason');
        if(!empty($refund_id) && !empty($refuse_reason)){
            $order_id = OrderRefund::where([['id',$refund_id],['refund_status',OrderRefund::ORDER_REFUND_SHOP_CHECKED]])->value('order_id');
            if(!empty($order_id)){
                $data['refuse_reason'] = $refuse_reason;
                $data['refund_status'] = OrderRefund::ORDER_REFUND_ADMIN_REFUSE;
                $res = OrderRefund::where('id',$refund_id)->update($data);
                $order_res = Order::where('id',$order_id)->update(['status'=>OrderService::ORDER_STATUS_APPLY_REFUND_SHOP_REFUSE,'update_time'=>time()]);
                if($res && $order_res){
                    OrderLog::addOrderLog($order_id,$this->users['id'],OrderLog::ORDER_LOG_OPERATE_TYPE_ADMIN,'订单退款-平台审核拒绝');
                    return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'审核拒绝成功');
                }else{
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL, '审核拒绝失败');
                }
            }else{
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '退款订单不存在或不是待审核状态');
            }
        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请选择要操作的订单并填写拒绝原因');
        }
    }


    /**
     * 已发货订单退款审核
     */
    public function orderRefundAuditList(Request $request)
    {
        $request_data = $request->all();
        $list = (new OrderRefundAudit())->checkList($request_data);

        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '获取成功', $list);
    }


    /**
     * 已发货订单退款审核
     */
    public function confirmRefundOrder(Request $request)
    {
        $dataAudit = OrderRefundAudit::find($request['id'])->toArray();
        if (empty($dataAudit) || $dataAudit['check_status']['value']) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '记录不存在或已审核');
        }
        if ($dataAudit['check_status']['value'] > 0) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '记录已审核');
        }

        if (empty($dataAudit['order_id']) ) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '参数错误');
        }

        $userToken = $request->header("Authorization");
        $user = NewAdmin::where(['token' => $userToken, 'type' => AuthService::MODEL_ADMIN])->first();
        $user = obToArray($user);

        if (md5($user['mobile'] . $request['password']) != $user['password']) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '密码输入错误错误');
        }

        $order = Order::from('sp_order_2 as o')->where('o.id', $dataAudit['order_id'])
            ->where('o.status', OrderService::ORDER_STATUS_DELIVER_SUCCESS)
            ->leftjoin('sp_shop_user_2 as s', 's.member_id', 'o.seller_id')
            ->leftjoin('sp_member_2 as m', 'm.id', 'o.uid')
            ->leftjoin('sp_order_goods_2 as og', 'og.order_id', 'o.id')
            ->lockForUpdate()
            ->select('o.id as order_id', 'o.mini_id','o.pay_type', 'o.status', 'o.rent_total', 'o.rights_auth_no', 'o.trade_no',
                'o.alipay_trade_no', 'o.seller_id', 'o.month_total', 'o.uid', 'o.realname', 'o.order_from',
                'o.is_skip', 's.shop_balance', 'og.goods_title', 'o.payer_user_id', 'og.goods_id', 'm.mobile', 'm.cert_name',
                'o.pay_time', 's.refund_check', 's.shopname', 'o.flow_id', 'o.rights_auth_no', 'o.alipay_trade_no')->first();
        $order = $order ? $order->toArray() : [];
        if (empty($order)) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单不存在或不是已发货状态');
        }
        $OrderLease = OrderLease::query()->where('order_id', $dataAudit['order_id'])
            ->where('status', 1)
            ->select(
                'id', 'which_period', 'rent', 'status'
            )
            ->first();
        $OrderLease = $OrderLease ? $OrderLease->toArray() : [];
        if (empty($OrderLease)) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '无付款记录');
        }


        if ($request['check'] == OrderLeaseAudit::CHECK_STATUS_AUDIT) {
                DB::beginTransaction();
                try {
                    OrderRefund::orderCloseAndRefund($order,$user['username']);
                    OrderRefundAudit::query()->where('id', $request['id'])->update(['check_status' => 1,  'operator_id' => $user['id']]);
                    DB::commit();
                } catch (\Exception $e) {
                    DB::rollBack();
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL, $e->getMessage());
                }
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '审核成功');
        }



        if ($request['check'] == OrderRefundAudit::CHECK_STATUS_REJECT) {
            $res = OrderRefundAudit::where('id', $request['id'])->update(['check_status' => 2, 'check_reason' => $request['check_reason'], 'operator_id' => $user['id']]);
            if ($res) {
                return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '审核成功');
            } else {
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '审核失败');
            }
        }
    }

    /**
     * 仅退款
     */
    public function OrderDeliverRefundApply(Request $request)
    {
        if (empty($request['orderId'])) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '参数错误');
        }
        $userToken = $request->header("Authorization");
        $user = NewAdmin::where(['token' => $userToken, 'type' => AuthService::MODEL_ADMIN])->first();
        $user = obToArray($user);

        if (md5($user['mobile'] . $request['password']) != $user['password']) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '密码输入错误错误');
        }


        if (empty($request['image_path'])) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请上传凭证图片');
        }
        if (empty($request['remark'])) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请上传备注说明');
        }



        $order = Order::from('sp_order_2 as o')->where('o.id', $request['orderId'])
            ->select(
                'o.id', 'o.flow_id', 'sign_status', 'pact_url', 'sign_no', 'trade_no'
            )
            ->first();
        $order = $order ? $order->toArray() : [];

        if (empty($order)) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单不存在');
        }

        $OrderLease = OrderLease::query()->where('order_id', $request['orderId'])
            ->where('status', 1)
            ->select(
                'id', 'which_period', 'status', 'rent',
            )
            ->first();
        $OrderLease = $OrderLease ? $OrderLease->toArray() : [];
        if (empty($OrderLease)) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单未支付');
        }

        $add = [
            'order_id' => $request['orderId'],
            'sub_remark' => $request['remark'],
            'image_path' => $request['image_path'],
            'create_time' => time(),
            'admin_id' => $user['id']
        ];
        $OrderLeaseAudit = OrderRefundAudit::query()->where('order_id', $request['orderId'])->value('check_status');
        if ($OrderLeaseAudit && $OrderLeaseAudit['value'] === 0 || $OrderLeaseAudit && $OrderLeaseAudit['value'] === 1) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请勿重复提交审核');
        }
        $audit_id = (new OrderRefundAudit)->insertGetId($add);
        if ($audit_id) {
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '提交申请成功');
        } else {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '更改失败');
        }
    }



}
